﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;
using WinDocker.Common.Global;

namespace WinDocker.UC
{
    public partial class DevSerCfgUC : UserControl
    {
        public DevSerCfgUC()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 容器程序用户控件实体类对像
        /// </summary>
        public DevSerCfgUCModel DevSerCfgUCModelObj = null;

        private string BaseDirPath = "";

        private void DevSerCfgUC_Load(object sender, EventArgs e)
        {
            try
            {
                this.BaseDirPath = AppDomain.CurrentDomain.BaseDirectory;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC DevSerCfgUC_Load Err:{ex.Message}");
            }
        }

        public void Show2()
        {
            try
            {
                var dev = this.DevSerCfgUCModelObj;
                if (dev == null)
                {
                    return;
                }
                this.lblSerName.Text = dev.DevSerName;

                var json = this.GetJsonByIsRunFile(out var s);
                var dy = Tool.ToDynamicsByJson(json).First();
                this.chkRun.Checked = dy.Get<bool>("isRun");

                try
                {
                    this.chkRun.CheckedChanged -= this.chkRun_CheckedChanged;
                }
                catch { }
                this.chkRun.CheckedChanged += this.chkRun_CheckedChanged;

                var cfgFilePath = $@"{this.BaseDirPath}{dev.DirPath}\{dev.CfgFileName}";
                this.lblMngUrl.Text = Tool.GetXMLAttribute(cfgFilePath, "WebApiUrl");

                try
                {
                    dev.EnableFieldName = (dev.EnableFieldName ?? "").Trim();
                    if (dev.EnableFieldName == "")
                    {
                        this.chkDisabled.Enabled = false;
                        return;
                    }
                    var yhConfigPath = $@"{this.BaseDirPath}{dev.DirPath}\{dev.CfgFileName}";
                    if (!File.Exists(yhConfigPath))
                    {
                        this.chkDisabled.Enabled = false;
                        return;
                    }
                    var sVal = (Tool.GetXMLAttribute(yhConfigPath, dev.EnableFieldName) ?? "").Trim();
                    if (sVal == "")
                    {
                        this.chkDisabled.Enabled = false;
                        return;
                    }
                    this.chkDisabled.Enabled = true;
                    this.chkDisabled.Checked = (!(sVal.Trim().ToLower() == "true"));
                    try
                    {
                        this.chkDisabled.CheckedChanged -= this.chkDisabled_CheckedChanged;
                    }
                    catch { }
                    this.chkDisabled.CheckedChanged += this.chkDisabled_CheckedChanged;
                }
                catch (Exception ex)
                {
                    LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC Show2 72Err:{ex.Message}");
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC Show2 Err:{ex.Message}");
            }
        }

        private string GetJsonByIsRunFile(out string filePath)
        {
            var sRet = "";
            filePath = "";
            try
            {
                var dev = this.DevSerCfgUCModelObj;
                if (dev == null)
                {
                    return sRet;
                }
                filePath = $@"{this.BaseDirPath}{dev.DirPath}\JtDFSer.json";
                sRet = File.ReadAllText(filePath, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC GetJsonByIsRunFile Err:{ex.Message}");
            }
            return sRet;
        }

        private void chkRun_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                CheckBox chk = (CheckBox)sender;
                var b = chk.Checked;
                var json = this.GetJsonByIsRunFile(out var filePath);
                var dy = Tool.ToDynamicsByJson(json).First();
                //this.chkRun.Checked = dy.Get<bool>("isRun");
                dy.Dy.isRun = b;
                var json2 = Newtonsoft.Json.JsonConvert.SerializeObject(dy.Dy);
                json2 = Tool.ConvertJsonString(json2);
                File.WriteAllText(filePath, json2, Encoding.UTF8);
                if (chk.Tag is bool)
                {
                    chk.Tag = null;
                    //LogWrite.TxtExport_DateNow("LogTest.txt", "DKE");
                    return;
                }
                MessageBox.Show($"{this.DevSerCfgUCModelObj.DevSerName}设置成{(b ? "启动" : "停止")}运行!\r\n", "提示");//【确记:重启服务之前要把这里的所有模块设置成运行状态】
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public object RunChkTag
        {
            set
            {
                this.chkRun.Tag = value;
            }
        }

        private void chkDisabled_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                var chk = (CheckBox)sender;
                var b = chk.Checked;
                var dev = this.DevSerCfgUCModelObj;
                var yhConfigPath = $@"{this.BaseDirPath}{dev.DirPath}\{dev.CfgFileName}";
                var b2 = Tool.SetXMLAttribute(yhConfigPath, dev.EnableFieldName, (!b).ToString());
                if (!b2)
                {
                    MessageBox.Show($"{this.DevSerCfgUCModelObj.DevSerName}设置成{(b ? "禁用" : "使用")}过程中,处理失败!", "提示");
                    chk.Checked = (!b);
                    return;
                }
                if (this.chkRun.Checked)
                {
                    this.chkRun.Tag = true;
                    this.chkRun.Checked = false;
                    System.Threading.Thread.Sleep(588);
                    this.chkRun.Tag = true;
                    this.chkRun.Checked = true;
                }
                MessageBox.Show($"{this.DevSerCfgUCModelObj.DevSerName}设置成{(b ? "禁用" : "使用")}!\r\n", "提示");
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC chkDisabled_CheckedChanged Err:{ex.Message}");
            }
        }

        /// <summary>
        /// 容器服务是否为运行状态
        /// </summary>
        public bool DevSerIsRun
        {
            get
            {
                return this.chkRun.Checked;
            }
        }

        private bool? ChkRunChecked = null;
        /// <summary>
        /// 设置容器服务模块的运行启用状态
        /// </summary>
        /// <param name="isRun"></param>
        public void SetDevSerRun(bool isRun)
        {
            try
            {
                //this.chkRun.Tag = true;
                //this.chkRun.Checked = isRun;

                if (isRun)
                {
                    return;
                }
                if (!this.chkRun.Checked)
                {
                    return;
                }
                this.ChkRunChecked = this.chkRun.Checked;
                this.chkRun.Tag = true;
                this.chkRun.Checked = isRun;
                System.Threading.Thread.Sleep(155);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC SetDevSerRun Err:{ex.Message}");
            }
        }

        /// <summary>
        /// 恢复容器服务模块的运行启用状态
        /// </summary>
        public void SetDevSerRun()
        {
            try
            {
                if (this.ChkRunChecked == null)
                {
                    return;
                }
                var b = (bool)this.ChkRunChecked;
                this.chkRun.Tag = true;
                this.chkRun.Checked = b;
                this.ChkRunChecked = null;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC SetDevSerRun 1 Err:{ex.Message}");
            }
        }
              

        /// <summary>
        /// 设置容器服务模块的运行启用状态(单个临时)
        /// </summary>
        /// <param name="isRun"></param>
        public void SetDevSerRunBySingle(bool isRun)
        {
            try
            {
                var ch = this.chkRun.Checked;
                if (ch == isRun)
                {
                    return;
                }
                this.chkRun.Checked = isRun;
                System.Threading.Thread.Sleep(125);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", $"DevSerCfgUC SetDevSerRunBySingle Err:{ex.Message}");
            }
        }


        private void lklOpenCfgFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                var dev = this.DevSerCfgUCModelObj;
                if (dev == null)
                {
                    return;
                }
                var yhConfigPath = $@"{this.BaseDirPath}{dev.DirPath}\{dev.CfgFileName}";
                if (!File.Exists(yhConfigPath))
                {
                    //this.lblY3MngUrl.Text = Tool.GetXMLAttribute(y3ConfigPath, "WebApiUrl");
                    MessageBox.Show("配置文件不存在!", "提示");
                    return;
                }
                System.Diagnostics.Process.Start("notepad.exe", yhConfigPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }

        private void lblSerName_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                var dev = this.DevSerCfgUCModelObj;
                if (dev == null)
                {
                    return;
                }
                var yhConfigPath = $@"{this.BaseDirPath}{dev.DirPath}\Log\{DateTime.Now.ToString("yyyy-MM-dd")}";
                if (!Directory.Exists(yhConfigPath))
                {
                    //MessageBox.Show($"文件夹({yhConfigPath})不存在!", "提示");
                    //return;
                    Directory.CreateDirectory(yhConfigPath); //新建文件夹  
                }
                //System.Diagnostics.Process.Start("notepad.exe", yhConfigPath);
                System.Diagnostics.Process.Start("explorer.exe", yhConfigPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }

        private void lblSerName_MouseEnter(object sender, EventArgs e)
        {
            try
            {
                var ct = (Control)sender;
                this.toolTip1.SetToolTip(ct, ct.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                var name = this.lblSerName.Text;
                //MessageBox.Show($"D:{name}");
                this.txtName.Text = name;
                this.pnlNameChange.Location = new Point((this.Width - this.pnlNameChange.Width) / 2, (this.Height - this.pnlNameChange.Height) / 2);
                this.pnlNameChange.Show();
                this.pnlNameChange.BringToFront();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }

        private void btnNameChange_Click(object sender, EventArgs e)
        {
            try
            {
                var dev = this.DevSerCfgUCModelObj;
                if (dev == null)
                {
                    this.pnlNameChange.Hide();
                    return;
                }
                var path = $"{this.BaseDirPath}NDAppConfig.json";
                if (!File.Exists(path))
                {
                    this.pnlNameChange.Hide();
                    return;
                }
                var json = File.ReadAllText(path, Encoding.UTF8);
                var lt = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DevSerCfgUCModel>>(json);
                var dev2 = lt.FirstOrDefault(p => p.DirPath == dev.DirPath);
                if (dev2 == null)
                {
                    this.pnlNameChange.Hide();
                    return;
                }
                dev2.DevSerName = (this.txtName.Text ?? "").Trim();
                json = Newtonsoft.Json.JsonConvert.SerializeObject(lt);
                json = Tool.ConvertJsonString(json);
                File.WriteAllText(path, json, Encoding.UTF8);
                this.pnlNameChange.Hide();
                this.lblSerName.Text = dev2.DevSerName;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Err:{ex.Message}");
            }
        }
    }
}
